package org.budo.oschina.api;

import org.budo.oschina.api.response.OschinaTokenResponse;
import org.budo.support.http.client.Request;
import org.budo.support.http.client.Response;
import org.budo.support.java.net.util.UrlEncodeUtil;

/**
 * @author lmw
 */
public class OschinaOauthApi extends AbstractOschinaApi {
    private static final String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36";

    public OschinaTokenResponse token(String code) {
        String url = "http://www.oschina.net/action/openapi/token" //
                + "?client_id=" + this.getAppKey() //
                + "&client_secret=" + this.getAppSecret() //
                + "&grant_type=authorization_code" //
                + "&code=" + code //
                + "&redirect_uri=" + UrlEncodeUtil.encode(this.getRedirectUri());

        Request tokenRequest = new Request();
        tokenRequest.setUserAgent(USER_AGENT);
        tokenRequest.setMethod(Request.GET);
        tokenRequest.setUrl(url);
        Response tokenResponse = tokenRequest.execute();

        return new OschinaTokenResponse(tokenResponse);
    }
}
